import { createRouter, createWebHistory, type Router, type RouteRecordRaw } from "vue-router";
import { emitter } from "@/utils/emitter";
import { authStore } from "@/store";

//获取所有的vue文件，vue3推荐使用这个
const modules = import.meta.glob("@/**/*.vue");

//定义静态路由（默认路由）
const staticRoutes: Array<RouteRecordRaw> = [
    {
        path: "/index",
        redirect: "/",
    },
    {
        name: "/",
        path: "/",
        component: () => import("@/views/index/Index.vue"),
    },
    {
        name: "/401",
        path: "/401",
        component: () => import("@/views/error/401.vue"),
    },
    {
        name: "/404",
        path: "/404",
        component: () => import("@/views/error/404.vue"),
    },
    {
        path: "/:pathMatch(.*)*",
        component: () => import("@/views/error/404.vue"),
    },
];

//暴露并创建路由
export const router: Router = createRouter({
    //history: createWebHashHistory(),
    history: createWebHistory(),
    routes: staticRoutes,
});

//路由前置守卫
router.beforeEach(async (to, _from, next) => {
    //1.状态库
    const store = authStore();

    //2.是否是静态路由里的路由，如果是直接放
    if (staticRoutes.map(route => route.path).findIndex((path) => path == to.path) > -1) {
        return next();
    }

    //3.判断token
    const token = store.accessToken;
    if (!token || token.trim().length == 0) {
        return next("/401");
    }

    //4.判断当前路由中是否有要去的路由
    const hasRouteIndex = router.getRoutes()?.map((route) => route.path)?.findIndex((path) => path == to.path);
    if (hasRouteIndex > -1) {
        return next();
    }

    //5.动态路由，查看pinia中是否有要去的路由
    const dynamicRoutes = store?.routes;
    const dynamicRouteIndex = dynamicRoutes?.map((route) => route.parentUri + "/" + route.childUri)?.findIndex((path) => path == to.path);
    if (dynamicRouteIndex == -1) {
        return next("/404");
    }

    //6.动态添加路由
    const route = dynamicRoutes[dynamicRouteIndex];
    router.addRoute({
        path: route.parentUri,
        name: route.parentUri,
        component: modules[`/src${route.parentComponent}`],
        children: [
            {
                name: route.childUri,
                path: route.childUri,
                component: modules[`/src/views${route.childComponent}`],
            },
        ],
    });
    next(to.path);
});

//重置路由
export const removeRoute = (): void => {
    router.getRoutes()
        .filter((route: any) => staticRoutes.findIndex((item: RouteRecordRaw) => item.path === route.path) < 0)
        .forEach((route: any) => router.removeRoute(route.name));
};

/**
 * 事件总线
 */
emitter.on("router-push", (path) => router.push(path));
emitter.on("router-remove", () => removeRoute());
